<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminCdjRole;
use App\Models\Admin\AdminMenu;
use Illuminate\Http\Request;
use Auth,DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use PhpParser\Node\Stmt\TryCatch;

class AdminRoleController extends AdminController
{
    use AdminTrait;

    protected $model;

    /**
     * 定义验证规则
     */
    protected $validate_rule = [
        'name' => 'required',
    ];

    /**
     * 定义验证错误信息
     */
    protected $err_msg = [
        'name.required' => '角色名称不能为空',
    ];

    /**
     * 定义列表排序
     */
    protected $orderBy = [
        'id' => 'asc',
    ];

    public function __construct(AdminCdjRole $model)
    {
        parent::__construct();
        $this->model = $model;
    }

    public function edit(BaseRequest $request)
    {
        //基础角色，不可以编辑
        $ids = [1];
        if (in_array($request->id,$ids)){
            return response()->json(['errcode'=>40008,'errmsg'=>'基础角色，不可操作']);
        }
        $info = $this->model->where('id',$request->id)->first();
        if(empty($info)){
            return response()->json(['errcode'=>40009,'errmsg'=>'信息不存在']);
        }
        //赋值
        foreach ($this->setRequestField($request->all(), true) as $k => $v) {
            if (!is_array($v)) {
                $info->$k = $v;
            }
        }
        $perInfo = $info->getOriginal();//获取修改之前的字段
        //执行修改操作
        $result = $info->save();
        $nextInfo = $info->getChanges();//获取修改之后的字段
        if ($result) {
            //Logs::add($request->path(), ':ID' . $info->id);
            if (method_exists($this->model,'addLog')){
                if (!empty($nextInfo)) {
                    $this->model->addLog($perInfo,$nextInfo,2);
                }
            }
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        } else {
            return response()->json(['errcode'=>40007,'errmsg'=>'修改失败']);
        }

    }

    protected function search($request){
        return $this->model->where([]);
    }

    protected function checkDelete($id){
        //基础角色，不可以编辑
        $ids = [1];
        if (in_array($id,$ids)){
            return ['errcode'=>40008,'errmsg'=>'基础角色，不可操作'];
        }
        //检查是否属于当前SAAS用的角色
        $info = $this->model->where('id',$id)->first();
        if(empty($info)){
            return ['errcode'=>40009,'errmsg'=>'信息不存在'];
        }
        //是否有关联
//        $auth = DB::table('admin_cdj_auth')->where('role_id',$id)->count();
        $user = DB::table('admin_user')->where('role_id',$id)->count();

        if($user > 0){
            return ['errcode'=>40010,'errmsg'=>"此角色已关联用户，不能删除"];
        }else{
            DB::table('admin_cdj_auth')->where('role_id',$id)->delete();//删除角色授权
            return true;
        }
    }

    public function auth(BaseRequest $request)
    {
        $id = $request->id;

        //判断合法性
        $ids = [1];
        if (in_array($request->id,$ids)){
            return response()->json(['errcode'=>40008,'errmsg'=>'基础角色，不可操作']);
        }
        $info = $this->model->where('id',$id)->first();
        if(empty($info)){
            return response()->json(['errcode'=>40009,'errmsg'=>'信息不存在']);
        }
        // session(['admin_role_id' => $id]);
        //当前登录用户所有有权限的菜单
        $list = AdminMenu::getAuthMenu($this->jwt_user_info->role_id);
//        dd($list->toArray());
        //二级菜单所有ID
        $ids = $list->pluck('selfNext')->map(function ($val,$key){
            $val = $val->pluck('id');
            return $val;
        })->collapse();
        //三级菜单集合
        $sonList = AdminMenu::whereIn('pid',$ids)->orderBy('ordid','asc')->get()->groupBy('pid');
        //把三级菜单组合进列表
        $list = $list->map(function($val,$key)use($sonList){
            $val->selfNext->transform(function ($v,$k)use($sonList){
                if($sonList->has($v->id)){
                    $v->selfNext = $sonList->get($v->id);
                }else{
                    $v->selfNext = [];
                }
                return $v;
            });
            return $val;
        });

        //选中角色已获得的权限菜单
        $yes = DB::table('admin_cdj_auth')->where('role_id',$id)->pluck('menu_id');
        //是否选中
        $list = $list->transform(function ($item, $key) use ($yes){
            //处理父级
            if($yes->contains($item->id)){
                $item->isSelect = true;
            }else{
                $item->isSelect = false;
            }
            //处理子级
            $item->selfNext->transform(function ($val, $ke) use ($yes){
                if(!empty($val->selfNext)){
                    //处理三级
                    $val->selfNext->transform(function ($v,$k)use($yes){
                        $v->selfNext = [];
                        if($yes->contains($v->id)){
                            $v->isSelect = true;
                        }else{
                            $v->isSelect = false;
                        }
                        return $v;
                    });
                }
                if($yes->contains($val->id)){
                    $val->isSelect = true;
                }else{
                    $val->isSelect = false;
                }
                return $val;
            });
            return $item;
        });
        return  response()->json(['errcode'=>0,'data'=>['list'=>$list],'errmsg'=>'ok']);
    }

    public function accredit(Request $request)
    {
        $input=$request->all();
        $rules=[
          'role_id'=>'required|integer|min:1|exists:admin_cdj_role,id',
          'ids'=>'required|nullable'
        ];
        $validator = Validator::make($input, $rules,$this->vali_msg);
        if($validator->fails())
            return $this->error(['-1',$validator->errors()->first()]);

        $admin_role_id = $request->role_id;
        $ids = json_decode(urldecode($request->ids),true);
        if(!is_array($ids))
        {
            return $this->error(['-1','ids非法参数']);
        }
        //组合新增数据
        $data = [];
        foreach ($ids as $val){
            $data[] = [
                'role_id' => $admin_role_id,
                'menu_id' => $val,
            ];
        }
        DB::beginTransaction();
        try {
            //先删除之前的记录
            DB::table('admin_cdj_auth')->where('role_id', $admin_role_id)->delete();
            //保存
            $result = DB::table('admin_cdj_auth')->insert($data);
            if (method_exists($this->model,'addLog')){
                $this->model->addLog(['name'=>$this->model->where('id',$admin_role_id)->first()->name],[],6,__FUNCTION__);
            }
            DB::commit();
            return response()->json(['errcode'=>0,'errmsg'=>'ok']);
        }
        catch (\Exception $exception)
        {
            DB::rollBack();
            return $this->error(['-1','授权失败']);
        }
    }

    protected function setRequestField($arr,$type=false){
        //过滤字段
        if(isset($arr['_token'])) unset($arr['_token']);
        if (isset($arr['sign'])) unset($arr['sign']);
        if (isset($arr['timeStamp'])) unset($arr['timeStamp']);
        return $arr;
    }

}
